package compress

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strconv"

	"github.com/garyburd/redigo/redis"
)

const (
	PATH_ROOT = "/home/acfun/goprojects/src/sora/dataDst/"
	ZIP_FIX   = false
)

type Volume struct {
	Bookid       int
	Volumeid     int
	Header       string
	Index        int
	Author       string
	Press        string
	Introduction string
	LastUpdate   string
	Name         string
	Imageurl     string
	Chapters     []Chapter
}
type Chapter struct {
	Id    int
	Title string
	Index string
}

func ScanBooksFromRedis() {
	c, _ := redis.Dial("tcp", ":6379")
	for i := 29; i < 1422; i++ {
		ss, err := redis.Strings(c.Do("SMEMBERS", "sora:"+strconv.Itoa(i)+":vset"))
		if err != nil || len(ss) == 0 {
			continue
		}
		for _, vid := range ss {
			CreateInfo(c, strconv.Itoa(i), vid)
			if ZIP_FIX {
				c.Do("SADD", "sora:qzip", vid)
			}
		}
	}
	c.Close()
}
func CreateInfo(c redis.Conn, bid string, vid string) {
	v, err := redis.Values(c.Do("HGETALL", "sora:"+bid+":"+vid))
	if err != nil {
		log.Fatal(err)
	}
	volume := &Volume{}
	redis.ScanStruct(v, volume)
	values, err := redis.Values(c.Do("SORT", "sora:"+bid+":"+vid+":cset",
		"BY", "sora:"+bid+":"+vid+":*->ChapterId",
		"GET", "sora:"+bid+":"+vid+":*->ChapterId",
		"GET", "sora:"+bid+":"+vid+":*->ChapterTitle",
		"GET", "sora:"+bid+":"+vid+":*->ChapterIndex"))
	if err := redis.ScanSlice(values, &volume.Chapters); err != nil {
		log.Fatal(err)
	}
	b, err := json.Marshal(volume)
	if err != nil {
		log.Fatal(err)
	}
	var file *os.File
	file, err = os.OpenFile(PATH_ROOT+vid+"/info.json", os.O_RDWR|os.O_TRUNC, 0744)
	if err != nil && os.IsNotExist(err) { // 不存在则创建
		file, _ = os.OpenFile(PATH_ROOT+vid+"/info.json", os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0744)
	}
	file.Write(b)
	file.Close()
	fmt.Println(vid)
}
